package com.blog.oguzhan.soapui.utils.datasource;

import java.util.Iterator;

public class Datasource<T extends Iterable<?>> {

	private String name;
	private T data;
	private Iterator<?> iterator;
	private boolean isIterated;
	private DatasourceLoop datasourceLoop;

	protected Datasource(String name) {
		super();
		this.name = name;
		this.isIterated = false;
		this.datasourceLoop = null;
	}
	
	public Datasource(String name, T data) {
		this(name);
		this.data = data;
		this.iterator = data.iterator();
	}

	public Object getNext() {
		if (isIterated && iterator.hasNext()) {
			Object next = iterator.next();
			isIterated = true;
			return next;
		}
		else {
			datasourceLoop.breakLoop();
			return null;
		}
	}
	
	public boolean isBroken() {
		return isIterated;
	}

	public boolean hasNext() {
		return iterator.hasNext();
	}
	
	public void iterate() throws IterationBrokenException{
		if (this.isIterated == false) {
			throw new IterationBrokenException();
		}
		else {
			this.isIterated = true;
		}
	}

	public DatasourceLoop getDatasourceLoop() {
		return datasourceLoop;
	}

	public void setDatasourceLoop(DatasourceLoop datasourceLoop) {
		this.datasourceLoop = datasourceLoop;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public T getData() {
		return data;
	}

	public void setData(T data) {
		this.data = data;
	}
	
	@Override
	public String toString() {
		return "Datasource [name=" + name + ", data=" + data + "]";
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((data == null) ? 0 : data.hashCode());
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Datasource<?> other = (Datasource<?>) obj;
		if (data == null) {
			if (other.data != null)
				return false;
		} else if (!data.equals(other.data))
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}

}
